package cn.wildfire.chat.kit.qrcode;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.media.MediaScannerConnection;
import android.net.Uri;
import android.os.Build;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.bumptech.glide.request.target.CustomViewTarget;
import com.bumptech.glide.request.transition.Transition;
import com.king.zxing.util.CodeUtils;
import com.sourcemuch.im.caiba.R;
import com.sourcemuch.im.caiba.R2;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import butterknife.BindView;
import cn.wildfire.chat.app.Config;
import cn.wildfire.chat.app.extendsion.utils.BitmapUtils;
import cn.wildfire.chat.kit.GlideApp;
import cn.wildfire.chat.kit.WfcBaseActivity;
import cn.wildfirechat.model.GroupInfo;
import cn.wildfirechat.model.UserInfo;

public class QRCodeActivity extends WfcBaseActivity {

    @BindView(R2.id.potriatImg)
    ImageView potriatImg;
    @BindView(R2.id.nickyName)
    TextView nickyName;
    private String title;
    private String logoUrl;
    private String qrCodeValue;

    private UserInfo userInfo; // 用户二维码数据
    protected GroupInfo groupInfo; // 群组二维码数据

    @BindView(R2.id.qrCodeImageView)
    ImageView qrCodeImageView;

    int logoSize = 50;

    public static Intent buildQRCodeIntent(Context context, String title, String logoUrl, String qrCodeValue) {
        Intent intent = new Intent(context, QRCodeActivity.class);
        intent.putExtra("title", title);
        intent.putExtra("logoUrl", logoUrl);
        intent.putExtra("qrCodeValue", qrCodeValue);
        return intent;
    }

    public static Intent buildQRCodeIntent(Context context, String title, String logoUrl, String qrCodeValue, UserInfo userInfo) {
        Intent intent = new Intent(context, QRCodeActivity.class);
        intent.putExtra("title", title);
        intent.putExtra("logoUrl", logoUrl);
        intent.putExtra("qrCodeValue", qrCodeValue);
        intent.putExtra("userInfo", userInfo);
        return intent;
    }

    public static Intent buildQRCodeIntent(Context context, String title, String logoUrl, String qrCodeValue, GroupInfo groupInfo) {
        Intent intent = new Intent(context, QRCodeActivity.class);
        intent.putExtra("title", title);
        intent.putExtra("logoUrl", logoUrl);
        intent.putExtra("qrCodeValue", qrCodeValue);
        intent.putExtra("groupInfo", groupInfo);
        return intent;
    }

    @Override
    protected void beforeViews() {
        super.beforeViews();
        Intent intent = getIntent();
        title = intent.getStringExtra("title");
        qrCodeValue = intent.getStringExtra("qrCodeValue");
        logoUrl = intent.getStringExtra("logoUrl");
        userInfo = intent.getParcelableExtra("userInfo");
        groupInfo = intent.getParcelableExtra("groupInfo");
    }

    @Override
    protected int contentLayout() {
        return R.layout.qrcode_activity;
    }

    @Override
    protected void onResume() {
        super.onResume();
        setToolbarOrReplaceType(true, 3);
        rightTxtView.setVisibility(View.VISIBLE);
        rightTxtView.setText("保存");
        setReplaceTitle(title, -1);
        setSearchLayoutVisibility(false);

        rightTxtView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Bitmap bitmap = ((BitmapDrawable) qrCodeImageView.getDrawable()).getBitmap();
                saveBitmap(bitmap);
            }
        });

    }

    /**
     * 保存方法
     */
    public void saveBitmap(Bitmap bitmap) {
        File f;
        String fileName = "qrCode" + System.currentTimeMillis() + ".jpg";
        f = new File(Config.PHOTO_SAVE_DIR, fileName);
        if (f.exists()) {
            f.delete();
        }
        try {
            FileOutputStream out = new FileOutputStream(f);
            bitmap.compress(Bitmap.CompressFormat.PNG, 90, out);
            out.flush();
            out.close();
            Toast.makeText(caiBaChatApp, "保存成功", Toast.LENGTH_SHORT).show();

            //其次把文件插入到系统图库
//            MediaStore.Images.Media.insertImage(this.getContentResolver(),
//                    f.getAbsolutePath(), fileName, null);
            // 通知图库更新
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
                MediaScannerConnection.scanFile(this, new String[]{f.getAbsolutePath()}, null,
                        new MediaScannerConnection.OnScanCompletedListener() {
                            @Override
                            public void onScanCompleted(String path, Uri uri) {
                                Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
                                mediaScanIntent.setData(uri);
                                sendBroadcast(mediaScanIntent);
                            }
                        });
            } else {
                String relationDir = f.getParent();
                File file1 = new File(relationDir);
                sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED, Uri.fromFile(file1.getAbsoluteFile())));
            }

//            sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse("file://" + f)));
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    @Override
    protected void afterViews() {
        setTitle(title);
        genQRCode();
    }

    private void genQRCode() {
        GlideApp.with(this)
                .asBitmap()
                .load(logoUrl)
                .placeholder(R.mipmap.ic_launcher_cailiao)
                .into(new CustomViewTarget<ImageView, Bitmap>(qrCodeImageView) {
                    @Override
                    public void onLoadFailed(@Nullable Drawable errorDrawable) {
                        // the errorDrawable will always be bitmapDrawable here
                        if (errorDrawable instanceof BitmapDrawable) {
                            Bitmap bitmap = ((BitmapDrawable) errorDrawable).getBitmap();
                            Bitmap qrBitmap = CodeUtils.createQRCode(qrCodeValue, 400,
                                    BitmapUtils.toSize(bitmap.copy(Bitmap.Config.ARGB_8888, true), logoSize, logoSize));
                            qrCodeImageView.setImageBitmap(qrBitmap);
                        }
                    }

                    @Override
                    public void onResourceReady(@NonNull Bitmap resource, @Nullable Transition transition) {
                        Bitmap bitmap = CodeUtils.createQRCode(qrCodeValue, 400,
                                BitmapUtils.toSize(resource.copy(Bitmap.Config.ARGB_8888, true), logoSize, logoSize));
                        qrCodeImageView.setImageBitmap(bitmap);
                    }

                    @Override
                    protected void onResourceCleared(@Nullable Drawable placeholder) {

                    }
                });
        try {
            /**
             * 设置用户信息
             * */
            if (userInfo != null) {
                nickyName.setText("" + userInfo.displayName);
                if (userInfo.portrait != null) {
                    Glide.with(this).load(userInfo.portrait).apply(new RequestOptions().centerCrop().placeholder(R.mipmap.avatar_def)).into(potriatImg);
                }
            }
            /**
             * 设置群组信息
             * */
            if (groupInfo != null) {
                nickyName.setText("" + groupInfo.name);
                if (groupInfo.portrait != null) {
                    Glide.with(this).load(groupInfo.portrait).apply(new RequestOptions().centerCrop().placeholder(R.mipmap.avatar_def)).into(potriatImg);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

}
